package com.peng.leetcode.tiger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Tiget2ListNodeSum
 *
 * <a href="https://leetcode-cn.com/problems/add-two-numbers/">链表相加</a>
 *
 * 使用哨兵当做头结点
 * 移动的时候需要判断节点为空
 * 需要处理最后一个节点相加 > 10 的情况
 *
 * @author lupeng
 * Created on 2022-04-17
 */
public class Tiget2ListNodeSum {

    private static final Logger logger = LoggerFactory.getLogger(Tiget2ListNodeSum.class);

    public static void main(String[] args) {

    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode solution(ListNode l1, ListNode l2) {
        ListNode sentry = new ListNode(0);
        ListNode curr = sentry;
        int prevSumRes = 0;
        while (l1 != null || l2 != null) {
            ListNode newListCrrNode = new ListNode();
            int sum = 0;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            sum += prevSumRes;
            if (sum >= 10) {
                prevSumRes = sum / 10;
                sum = sum % 10;
            } else {
                prevSumRes = 0;
            }
            newListCrrNode.val = sum;

            curr.next = newListCrrNode;
            curr = curr.next;
        }
        if (prevSumRes != 0) {
            curr.next = new ListNode(prevSumRes);
        }
        return sentry.next;
    }


}
